package com.lagou.edu.spring.core.defaults;

import com.lagou.edu.spring.core.ObjectFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 早期对象工厂
 *
 * @author 大犬
 * @date 2020/4/2
 */
public class EarlyBeanFactory {

    private Map<String, Object> earlyBeanMap;

    private Map<String, Object> originBeanMap;


    public EarlyBeanFactory() {
        earlyBeanMap = new HashMap<>(10);
        originBeanMap = new HashMap<>(10);
    }

    public void deleteEarlyBean(String beanName) {
        originBeanMap.remove(beanName);
        earlyBeanMap.remove(beanName);
    }

    public void addOriginBean(String beanName, Object originBean) {
        originBeanMap.put(beanName, originBean);
    }

    public void addEarlyBean(String beanName, Object earlyBean) {
        earlyBeanMap.put(beanName, earlyBean);
    }

    public Object getEarlyBean(String beanName, Boolean exposeEarlyBean) {
        Object earlyBean = earlyBeanMap.get(beanName);
        if (earlyBean == null) {
            return null;
        }
        // 如果允许早期暴露，则返回早期对象
        if (exposeEarlyBean) {
            // 如果早期对象是ObjectFactory，则需要调用ObjectFactory的方法获取到早期对象
            if (earlyBean instanceof ObjectFactory) {
                // 需要早期增强
                Object earlyWrapperBean = ((ObjectFactory) earlyBean).get();
                // 替换原始bean
                originBeanMap.put(beanName, earlyWrapperBean);
                return earlyWrapperBean;
            }
            // 返回早期对象
            return earlyBean;
        } else {
            if (earlyBean instanceof ObjectFactory) {
                return null;
            }
        }
        return originBeanMap.get(beanName);
    }

    public void clear() {
        originBeanMap.clear();
        earlyBeanMap.clear();
    }
}
